package com.orangeforms.webadmin.upms.service.impl;

import com.orangeforms.common.core.base.dao.BaseDaoMapper;
import com.orangeforms.common.core.base.service.BaseService;
import com.orangeforms.common.core.upload.BaseUpDownloader;
import com.orangeforms.common.core.util.MyDateUtil;
import com.orangeforms.webadmin.config.ApplicationConfig;
import com.orangeforms.webadmin.upms.dao.BusinessAttachResourceMapper;
import com.orangeforms.webadmin.upms.dao.BusinessCollectionMapper;
import com.orangeforms.webadmin.upms.dao.BusinessVisibleResourceMapper;
import com.orangeforms.webadmin.upms.model.AttachResource;
import com.orangeforms.webadmin.upms.model.VisibleResource;
import com.orangeforms.webadmin.upms.service.BusinessDigitalResourceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：howlrou
 * @Date：2024/8/12 15:33
 */
@Slf4j
@Service("businessDigitalResourceService")
public class BusinessDigitalResourceServiceImpl extends BaseService<VisibleResource, Long>
        implements BusinessDigitalResourceService {

    @Autowired
    BusinessVisibleResourceMapper visibleResourceMapper;

    @Autowired
    BusinessAttachResourceMapper attachResourceMapper;

    @Autowired
    BusinessCollectionMapper collectionMapper;

    @Autowired
    ApplicationConfig applicationConfig;

    @Override
    protected BaseDaoMapper<VisibleResource> mapper() {
        return visibleResourceMapper;
    }


    /**
     * 查询数字资源存储
     *
     * @param digitalResourceId 数字资源存储主键
     * @return 数字资源存储
     */
    @Override
    public VisibleResource selectVisibleResourceByDigitalResourceId(Long digitalResourceId) {
        return visibleResourceMapper.selectDigitalResourceByDigitalResourceId(digitalResourceId);
    }

    /**
     * 查询附件资源存储
     *
     * @param digitalResourceId 附件资源存储主键
     * @return 附件资源存储信息
     */
    public AttachResource selectAttachResourceByDigitalResourceId(Long digitalResourceId) {
        return attachResourceMapper.selectDigitalResourceByDigitalResourceId(digitalResourceId);
    }

    ;

    /**
     * 查询可预览资源存储列表
     *
     * @param visibleResource 可预览资源存储
     * @return 可预览资源存储
     */
    @Override
    public List<VisibleResource> selectVisibleResourceList(VisibleResource visibleResource) {
        return visibleResourceMapper.selectDigitalResourceList(visibleResource);
    }


    /**
     * 查询附件资源存储列表
     *
     * @param attachResource 附件资源存储
     * @return 附件资源存储集合
     */
    public List<AttachResource> selectAttachResourceList(AttachResource attachResource) {
        return attachResourceMapper.selectDigitalResourceList(attachResource);
    }

    ;


    /**
     * 新增数字资源存储
     *
     * @param visibleResource 数字资源存储
     * @return 结果
     */
    @Override
    public int insertVisibleResource(VisibleResource visibleResource) {
        visibleResource.setCreateTime(MyDateUtil.getNowDate());
        return visibleResourceMapper.insertDigitalResource(visibleResource);
    }

    /**
     * 新增附件资源存储
     *
     * @param attachResource 附件资源存储
     * @return 结果
     */
    public int insertAttachResource(AttachResource attachResource) {
        attachResource.setCreateTime(MyDateUtil.getNowDate());
        return attachResourceMapper.insertDigitalResource(attachResource);
    }

    ;


    /**
     * 修改数字资源存储
     *
     * @param visibleResource 数字资源存储
     * @return 结果
     */
    @Override
    public int updateVisibleResource(VisibleResource visibleResource) {
        visibleResource.setUpdateTime(MyDateUtil.getNowDate());
        return visibleResourceMapper.updateVisibleResource(visibleResource);
    }

    /**
     * 修改附件资源存储
     *
     * @param attachResource 附件资源存储对象
     * @return 结果
     */
    public int updateAttachResource(AttachResource attachResource) {
        attachResource.setUpdateTime(MyDateUtil.getNowDate());
        return attachResourceMapper.updateAttachResource(attachResource);
    }

    /**
     * 修改文件资源名称
     *
     * @param oldName
     * @param newName
     */
    public void updateAttachResource(String oldName, String newName) {
        // 指定原始文件路径
        File oldFile = new File(oldName);

        // 指定新的文件路径
        File newFile = new File(newName);
        if (oldFile.renameTo(newFile)) {
            log.info("文件重命名成功！");
        } else {
            log.error("文件重命名失败！");
        }
    }

    /**
     * 批量删除数字资源存储
     *
     * @param digitalResourceIds 需要删除的数字资源存储主键
     * @return 结果
     */
    @Override
    public int deleteDigitalResourceByDigitalResourceIds(Long[] digitalResourceIds) {
        return visibleResourceMapper.deleteDigitalResourceByDigitalResourceIds(digitalResourceIds);
    }

    /**
     * 删除资源存储信息
     *
     * @param digitalResourceId 数字资源存储主键
     * @return 结果
     */
    @Override
    public int deleteDigitalResourceByDigitalResourceId(Long digitalResourceId) {
        return visibleResourceMapper.deleteDigitalResourceByDigitalResourceId(digitalResourceId);
    }


    // 删除多个文件并修改可预览资源表
    public Integer deleteFiles(Long digitalResourceId, String[] filePaths) {
        int count = 0;
        ArrayList<String> deleteFilePaths = new ArrayList<>();
        for (String filePath : filePaths) {
            File file = new File(applicationConfig.getUploadFileBaseDir() + "/" + filePath);
            if (file.exists()) {
                if (file.delete()) {
                    count++;
                    deleteFilePaths.add(filePath);
                } else {
                    log.error("文件删除失败：" + filePath);
                }
            } else {
                log.error("文件不存在：" + filePath);
            }
        }
//        //修改可预览数据表
//        VisibleResource existVisibleResource = VisibleResourceMapper.selectDigitalResourceByDigitalResourceId(digitalResourceId);
//        if (null != existVisibleResource) {
//            VisibleResource updateVisibleResource = new VisibleResource();
//            List<String> existFilePath = MyListUtil.stringSplit(existVisibleResource.getFilePath());
//            ArrayList<String> arrayExistFilePath = new ArrayList<>(existFilePath);
//            arrayExistFilePath.removeIf(deleteFilePaths::contains);
//            updateVisibleResource.setDigitalResourceId(existVisibleResource.getDigitalResourceId());
//            updateVisibleResource.setFilePath(MyListUtil.listToString(arrayExistFilePath));
//            VisibleResourceMapper.updateDigitalResource(updateVisibleResource);
//
//        }
        return count;
    }


    // 删除多个文件
    public Integer deleteFiles(String[] filePaths) {
        int count = 0;
        for (String filePath : filePaths) {
            File file = new File(applicationConfig.getUploadFileBaseDir() + "/" + filePath);
            if (file.exists()) {
                if (file.delete()) {
                    System.out.println("文件已成功删除：" + filePath);
                    count++;
                } else {
                    log.error("文件删除失败：" + filePath);
                }
            } else {
                log.error("文件不存在：" + filePath);
            }
        }
        return count;
    }


    // 删除单个可预览文件以及sql表记录
    public Integer deleteVisibleFile(Long digitalResourceId, String filePath) {

        File file = new File(applicationConfig.getUploadFileBaseDir() + "/" + filePath);
        if (file.exists()) {
            if (file.delete()) {
                System.out.println("文件已成功删除：" + filePath);
            } else {
                log.error("文件删除失败：" + filePath);
            }
        } else {
            log.error("文件不存在：" + filePath);
        }
        visibleResourceMapper.deleteDigitalResourceByDigitalResourceId(digitalResourceId);
        return 1;
    }

    // 删除单个附件文件资源以及sql表记录
    public Integer deleteAttachFile(Long digitalResourceId, String filePath) {

        File file = new File(applicationConfig.getUploadFileBaseDir() + "/" + filePath);
        if (file.exists()) {
            if (file.delete()) {
                System.out.println("文件已成功删除：" + filePath);
            } else {
                log.error("文件删除失败：" + filePath);
            }
        } else {
            log.error("文件不存在：" + filePath);
        }
        attachResourceMapper.deleteDigitalResourceByDigitalResourceId(digitalResourceId);
        return 1;
    }

    /**
     * 删除附件
     *
     * @param attachResource
     * @return
     */
    public void deleteFiles(AttachResource attachResource) {
        String filePath = attachResource.getFilePath();
        Long digitalResourceId = attachResource.getDigitalResourceId();
        File file = new File(applicationConfig.getUploadFileBaseDir() + "/" + filePath);
        if (file.exists()) {
            if (file.delete()) {
                log.info("文件已成功删除：" + filePath);

            } else {
                log.error("文件删除失败：" + filePath);
            }
        } else {
            log.error("文件不存在：" + filePath);
        }
        if (null != digitalResourceId && digitalResourceId != 0) {
            attachResourceMapper.deleteDigitalResourceByDigitalResourceId(digitalResourceId);
        }
    }


    /**
     * 扫描藏品指定目录将资源记录录入数据表
     *
     * @param collectionIds
     */
    public void scanResource(List<Long> collectionIds) {
        for (Long collectionId : collectionIds) {
            String enterId = collectionMapper.selectEnterById(collectionId);
            String visiblePath = BaseUpDownloader.makeScanPath(applicationConfig.getUploadFileBaseDir(), true, enterId);
            File visibleDirectory = new File(visiblePath);
            if (visibleDirectory.exists() && visibleDirectory.isDirectory()) {
                visibleResourceMapper.deleteByCollectionId(collectionId);
                File[] visibleFiles = visibleDirectory.listFiles();
                for (File file : visibleFiles) {
                    VisibleResource visibleResource = new VisibleResource();
                    String fileName = file.getName();
                    String extension = FilenameUtils.getExtension(fileName);
                    visibleResource.setCollectionId(collectionId);
                    visibleResource.setResourceType(extension);
                    visibleResource.setFileName(fileName);
                    visibleResource.setFilePath(BaseUpDownloader.makeResourceSavePath(true, enterId) + "/" + fileName);
                    visibleResource.setCreateTime(MyDateUtil.getNowDate());
                    visibleResourceMapper.insertDigitalResource(visibleResource);
                }
            }

            String attachPath = BaseUpDownloader.makeScanPath(applicationConfig.getUploadFileBaseDir(), false, enterId);
            File attachDirectory = new File(attachPath);
            if (attachDirectory.exists() && attachDirectory.isDirectory()) {
                attachResourceMapper.deleteByCollectionId(collectionId);
                File[] attachFiles = attachDirectory.listFiles();
                for (File file : attachFiles) {
                    AttachResource attachResource = new AttachResource();
                    String fileName = file.getName();
                    String extension = FilenameUtils.getExtension(fileName);
                    attachResource.setCollectionId(collectionId);
                    attachResource.setResourceType(extension);
                    attachResource.setFileName(fileName);
                    attachResource.setFilePath(BaseUpDownloader.makeResourceSavePath(true, enterId) + "/" + fileName);
                    attachResource.setCreateTime(MyDateUtil.getNowDate());
                    attachResourceMapper.insertDigitalResource(attachResource);
                }
            }

        }

    }


}
